import ecdsa
from ecdsa.util import sigencode_der, sigdecode_der
from hashlib import sha256

# https://zhuanlan.zhihu.com/p/100736598


class Request:

    # byte order BigEndian
    # x = int.from_bytes(xy[:32], byteorder='big')
    # y = int.from_bytes(xy[32:], byteorder='big')
    # signing_key.curve.generator.curve().contains_point(x, y)

    def sign(self, sign_key: ecdsa.SigningKey, hash_func, data: bytes, nonce: int) -> bytes:
        verify_key = sign_key.verifying_key

        # serialize a request.
        serialized_req = []
        xy = verify_key.to_string()
        nonce_bytes = nonce.to_bytes(8, byteorder='big', signed=False)
        serialized_req.extend(nonce_bytes)
        serialized_req.extend(data)
        serialized_req.extend(xy)

        # signature of the request
        sign = sign_key.sign_deterministic(
            bytes(serialized_req), hashfunc=hash_func, sigencode=sigencode_der)
        serialized_req.extend(sign)
        self.with_sign = bytes(serialized_req)
        return sign


msp_dir = "/mnt/e/fabricdev/fabric-samples/test-network/organizations/peerOrganizations/org1.example.com/users/User1@org1.example.com/msp"
key_file = "/keystore/priv_sk"
signing_key = ecdsa.SigningKey.from_pem(open(f"{msp_dir}{key_file}").read())

if __name__ == "__main__":
    req = Request()
    hash = sha256()
    hash.update(b"message")
    req.sign(signing_key, sha256, hash.digest(), 1)
    print(req.with_sign)
    print(len(req.with_sign))
